package mao.thinkinjava.concurency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimplePriority implements Runnable{
    private static int count=0;
    private final int id=count++;
    private volatile double d;
    private int countDown=5;

    private int priority;

    public SimplePriority(int priority){
        this.priority=priority;
    }


    @Override
    public String toString() {
        return "SimplePriority{" +
                "id=" + id +
                ", d=" + d +
                ", countDown=" + countDown +
                ", priority=" + priority +
                '}';
    }

    @Override
    public void run() {
        Thread.currentThread().setPriority(priority);
        while (true) {
            for (int i = 0; i < 100000; i++) {
                d += (Math.E + Math.PI) / (double) i;
                if (i % 1000 == 0) {
                    //  System.out.println(this);
                   // Thread.yield();
                }
            }
            System.out.println(this);
            if(--countDown == 0){
                return;
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        //由于计算机是多核的，需要多启动线程才能看点优先级的效果。
        for (int i = 0; i < 10; i++) {
            exec.execute(new SimplePriority(Thread.MIN_PRIORITY));
        }
        for (int i = 0; i < 10; i++) {
            exec.execute(new SimplePriority(Thread.MAX_PRIORITY));
        }
        exec.shutdown();
    }
}
